package admin

import (
	"MBGAdmin/models"
	"MBGAdmin/util"
	"github.com/astaxie/beego/orm"
	"golang.org/x/crypto/bcrypt"
	"strconv"
	"time"
)

// 管理员控制器
type AdminController struct {
	AuthController
}

// 管理员首页
func (c *AdminController) Get() {
	c.Display("admin/admin/index.html")
}

// 管理员列表获取
func (c *AdminController) GetLists() {
	page, _ := strconv.Atoi(c.GetString("page"))
	limit, _ := strconv.Atoi(c.GetString("limit"))
	o := orm.NewOrm()
	p := o.QueryTable(models.Admins{})
	// 条件筛选
	if username := c.GetString("username"); username != "" {
		p = p.Filter("username__contains", username)
	}
	if mobile := c.GetString("mobile"); mobile != "" {
		p = p.Filter("mobile__contains", mobile)
	}
	if status := c.GetString("status"); status != "" {
		p = p.Filter("status", status)
	}
	// 根据page和limit取数据
	var admins []*models.Admins
	_, err := p.Offset((page - 1) * limit).Limit(limit).RelatedSel().OrderBy("id").All(&admins)
	count, _ := p.Count()
	if err != nil {
		c.BaseResponse(1, "获取列表失败:"+err.Error())
		return
	}
	// 封装结果
	rsp := make(map[string]interface{})
	rsp["count"] = count
	rsp["lists"] = admins
	c.BaseResponse(0, "获取列表成功", rsp)
}

// 删除管理员
func (c *AdminController) Delete() {
	id, _ := c.GetInt(":id")
	if id == 1 {
		c.BaseResponse(1, "系统管理员不可删除")
		return
	}
	admin := models.Admins{Id: id}
	err := admin.DeleteAdminsById()
	if err != nil {
		c.BaseResponse(1, "删除管理员失败："+err.Error())
		return
	}
	c.BaseResponse(0, "删除管理员成功")
}

// 添加管理员页面
func (c *AdminController) CreateView() {
	// 获取所有roles
	o := orm.NewOrm()
	var roles []models.Roles
	_, _ = o.QueryTable(models.Roles{}).Filter("status", 1).All(&roles)
	c.Data["roles"] = roles
	c.Display("admin/admin/create.html")
}

// 添加管理员
func (c *AdminController) Create() {
	// 解析表单参数
	admin := models.Admins{}
	if err := c.ParseForm(&admin); err != nil {
		c.BaseResponse(1, "解析表单出错："+err.Error())
		return
	}
	// 封装admin结构体
	admin.Role = &models.Roles{}
	admin.Role.Id, _ = c.GetInt("role_id")
	admin.LoginNum = 0
	admin.LastLoginTime = orm.ToStr(time.Now().Unix())
	admin.LastLoginIp = c.Ctx.Input.IP()
	// 将密码加密
	passwordHash, _ := bcrypt.GenerateFromPassword([]byte(admin.Password), bcrypt.DefaultCost)
	admin.Password = util.GoLangToPhp(string(passwordHash))
	// 插入数据库
	if err := admin.AddAdmins(); err != nil {
		c.BaseResponse(1, "创建管理员失败："+err.Error())
		return
	}
	c.BaseResponse(0, "创建管理员成功")
}

// 编辑管理员页面
func (c *AdminController) UpdateView() {
	// 解析ID
	id, err := c.GetInt(":id")
	if err != nil {
		c.BaseResponse(1, "解析ID错误,请刷新页面后重试")
		return
	}
	// 根据ID获取admin
	admin := models.Admins{Id: id}
	err = admin.GetAdminsById()
	if err != nil {
		c.BaseResponse(1, "ID不存在,请刷新页面后重试")
		return
	}
	c.Data["admin"] = admin
	// 获取所有可用role
	o := orm.NewOrm()
	var roles []models.Roles
	_, _ = o.QueryTable(models.Roles{}).Filter("status", 1).All(&roles)
	c.Data["roles"] = roles
	c.Display("admin/admin/update.html")
}

// 编辑管理员
func (c *AdminController) Update() {
	// 解析表单参数
	adminNew := models.Admins{}
	if err := c.ParseForm(&adminNew); err != nil {
		c.BaseResponse(1, "解析表单出错："+err.Error())
		return
	}
	// 解析ID
	id, err := c.GetInt(":id")
	if err != nil {
		c.BaseResponse(1, "ID解析失败")
		return
	}
	// 根据ID查找数据库是否存在
	adminOld := models.Admins{Id: id}
	err = adminOld.GetAdminsById()
	if err != nil {
		c.BaseResponse(1, "ID不存在")
		return
	}
	// 封装修改参数
	adminOld.Role.Id, _ = c.GetInt("role_id")
	adminOld.Username = adminNew.Username
	adminOld.Mobile = adminNew.Mobile
	adminOld.Email = adminNew.Email
	adminOld.Status = adminNew.Status
	// 判断是否修改密码
	if adminNew.Password != "" {
		passwordHash, _ := bcrypt.GenerateFromPassword([]byte(adminNew.Password), bcrypt.DefaultCost)
		adminOld.Password = util.GoLangToPhp(string(passwordHash))
	}
	// 根据ID修改数据
	err = adminOld.UpdateAdminsById()
	if err != nil {
		c.BaseResponse(1, "修改失败"+err.Error())
		return
	}
	c.BaseResponse(0, "修改成功")
}
